import 'dart:convert';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/response/machine_model.dart';
import 'package:test_flutter/model/response/service_model.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:test_flutter/widgets/Button.dart';
import 'package:test_flutter/widgets/DryingTargetHero.dart';
import 'package:flutter/services.dart';

class DryingDetailPage extends StatefulWidget {
  final int position;
  final ServiceModel bean;

  DryingDetailPage(this.position, this.bean);

  @override
  DryingDetailPageState createState() => new DryingDetailPageState();
}

class DryingDetailPageState extends State<DryingDetailPage> {

  bool _saving = false;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(colors: [Color(0xFF18D48B), Color(0xFFFFF68F)])),
            child: new AppBar(
              primary: true,
              title: new Text(widget.bean.Remark),
              backgroundColor: Colors.transparent,

            ),
          ),
          preferredSize: new Size(Fit.scaleX(1080), kToolbarHeight)),
      body: ModalProgressHUD(
        inAsyncCall: _saving,
        child: SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.all(Fit.scaleX(10)),
            child: Column(
              children: <Widget>[
                Center(
                    child: Card(
                        child:
                            new DryingTargetHero(widget.position, widget.bean))),
                Center(
                    child: Container(
                        padding:
                            EdgeInsets.only(top: Fit.scaleY(200)),
                        child: new Button(CustomLocalizations.instance.getString(StringIds.scanThePayment), onPressed: setOnclick))),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void setOnclick() {
    scan(widget.bean.Id);
  }

  Future scan(int id) async {
    try {
      String barcode = await BarcodeScanner.scan();
      MachineModel machineModel = MachineModel.fromJson(json.decode(barcode));
      scanPay(id,machineModel.sn);
      print(barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        ToastUtil.showToast('The user did not grant the camera permission!');
      } else {
        ToastUtil.showToast('Unknown error: $e');
      }
    }on Exception catch (e)  {
      if(e.toString().contains('Invalid envelope')){
        ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.cancelScan));
      }
      if(e.toString().contains('Unexpected character')){
        ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.invalidQrCode));
      }
    }
  }



  //扫描支付
  scanPay(int id, String Sn) async {
    setState(() {
      _saving = true;
    });


    Map<String, String> requestMap = new Map();
    requestMap['ServiceId'] = id.toString();
    requestMap['Sn'] = Sn;
    requestMap['LocalSeq'] = DateTime.now().millisecondsSinceEpoch.toString();



    DioUtil.getInstance(context).post(
        Api.scanPay,
            (response) {
          if (response.data['code'] == 1) {
            ToastUtil.showToast("授权成功,启动洗衣机");

          } else {
            ToastUtil.showToast(response.data['msg']);
          }
          setState(() {
            _saving = false;
          });
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error=========================:" + errorMsg);
          ToastUtil.showToast(errorMsg);
          setState(() {
            _saving = false;
          });
        });
  }
}
